<?php

namespace tools\lib\main\controller;

use tools\lib\main\Common;

/**
 * 创建控制
 * Class Controller
 * @package app\common\command\create\file
 */
class Controller extends Common
{
    /**
     * @var bool
     */
    protected $suffix = false;

    protected $return_class = '';

    /**
     *
     */
    protected function init()
    {
        parent::init();

        if (empty($this->parameter->getModule())) {
            dump('请使用-m|--module设置模块信息');
        }
    }

    /**
     * @return string
     */
    protected function service()
    {
        return ucfirst($this->className()) . 'Service';
    }

    /**
     * @return string
     */
    protected function template()
    {
        $class_name = transToPascal($this->parameter->getName());

        $service = $this->service();

        $server_namespace = $this->getFileProperties('service_namespace') ?: $this->getFileProperties('namespace');
        $use_service = $server_namespace . '\\' . $service;

        $return = config('controller.controller_return') ?: 'magein\php_tools\think\ApiReturn';
        $this->return_class = substr($return, strripos($return, '\\') + 1);

        $template = <<<EOT
<?php

{$this->getFileNamespace()}

{$this->getFileUse()}
use $return;
use $use_service;
use think\\Request;

class $class_name
{
    public function getList()
    {
        \$instance = {$service}::instance();
        
        \$result = \$instance->getList();
        
        if (\$result) {
            return $this->return_class::instance()->success(\$result);
        }
         
        return $this->return_class::instance()->error(\$instance);
    }
    
    public function getInfo(\$id)
    {    
        \$instance = {$service}::instance();
        
        \$result = \$instance->getInfo(\$id);
        
        if (\$result) {
            return $this->return_class::instance()->success(\$result);
        }
         
        return $this->return_class::instance()->error(\$instance);
    }
}
EOT;
        return $template;
    }


    protected function callback()
    {
        $action = $this->parameter->getAction();

        $params = $this->parameter->getParams();

        $content = product($params, '\think\response\Json');

        $service = $this->service();

        $template = <<<EOF
    public function $action()
    {
        \$instance = {$service}::instance();
        
        {$content['accept']}
        
        \$result = \$instance->$action({$content['input_param']});
        
        if (\$result) {
            return $this->return_class::instance()->success(\$result);
        }
         
        return $this->return_class::instance()->error(\$instance);
    }       
EOF;

        return append($this->savePath(), $template);
    }
}